import fse from 'fs-extra';
import path from 'path';
import fs from 'fs';
import { uploadBasePath } from '../config/app';

const saveFile = (filePath: any, distPath: string) => {
  return new Promise((resolve, reject) => {
    const render = fs.createReadStream(filePath);
    // Create a write stream
    const upStream = fs.createWriteStream(distPath);
    render.pipe(upStream);
    upStream.on('finish', () => {
      resolve(path);
    });
    upStream.on('error', err => {
      reject(err);
    });
  });
};

export async function uploadFile(file: any, type: string = 'files') {
  try {
    const uploadDir = '/uploads/' + type + '/';
    const filePath = uploadDir + file.name; // 文件名
    const uploadFilePath = uploadBasePath + uploadDir; // 存储的文件路录
    const distPath = uploadBasePath + uploadDir + file.name; // 绝对完整路径

    // 创建文件存放目录
    await fse.ensureDir(uploadFilePath);
    // 保存文件
    await saveFile(file.path, distPath);
    return filePath;
  } catch (error) {
    throw error;
  }
}
